import json
import os

from alipay import AliPay
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseForbidden, JsonResponse, HttpResponseNotFound, HttpResponseServerError
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View

from goods.models import SKU
from orders.models import OrderInfo, OrderGoods
from payment.models import Payment
from xiaoyu_mall_new import settings
from xiaoyu_mall_new.utils.response_code import RETCODE
from xiaoyu_mall_new.utils.views import LoginRequiredJSONMixin


class PaymentView(LoginRequiredJSONMixin, View):

    def get(self, request, order_id):
        # 获取登录用户
        user = request.user
        # 查询待支付订单
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden('订单信息错误')
        # 创建支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID, app_notify_url=None,
            app_private_key_string=open(os.path.join(os.path.dirname(__file__), 'keys/app_private_key.pem')).read(),
            alipay_public_key_string=open(os.path.join(os.path.dirname(__file__), 'keys/alipay_public_key.pem')).read(),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG,
        )
        # 生成支付宝登录链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='小鱼商城%s' % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(View):
    # 保存订单支付结果
    def get(self, request):
        # 获取到所有查询字符串参数
        query_dict = request.GET
        # 转换成字典类型
        data = query_dict.dict()
        # 移除sign
        signature = data.pop('sign')
        alipay = AliPay(
            appid=settings.ALIPAY_APPID, app_notify_url=None,
            app_private_key_string=open(
                os.path.join(os.path.dirname(__file__)), 'keys/app_private_key.pem').read(),
            alipay_public_key_string=open(
                os.path.join(os.path.dirname(__file__), 'keys/alipay_public_key.pem')).read(),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG,
        )

        success = alipay.verify(data, signature)
        if success:
            order_id = data.get('out_trade_no')
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id, trade_id=trade_id,
            )
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
            )

            context = {'trade_id': trade_id}

            return render(request, 'pay_success.html', context)
        else:
            return redirect(reverse('users:myorderinfo'))


class OrderCommentView(LoginRequiredMixin, View):
    """对订单的评价"""

    def get(self, request):
        """查询未评价的商品"""
        order_id = request.GET.get('order_id')

        try:
            OrderInfo.objects.get(order_id=order_id, user=request.user)
        except OrderInfo.DoesNotExist:
            return HttpResponseNotFound('订单不存在')

        try:
            uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False)
        except Exception:
            return HttpResponseServerError('订单商品信息出错')
        uncomment_goods_list = []
        for goods in uncomment_goods:
            uncomment_goods_list.append({
                'order_id': goods.order_id,
                'sku_id': goods.sku.id,
                'name': goods.sku.name,
                'price': str(goods.price),
                'default_image_url': settings.STATIC_URL + 'images/goods/' + goods.sku.default_image.url + '.jpg',
                'comment': goods.comment,
                'score': goods.score,
                'is_anonymous': str(goods.is_anonymous)
            })

        context = {'uncomment_goods_list': uncomment_goods_list}
        return render(request, 'goods_judge.html', context)

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        order_id = json_dict.get('order_id')
        sku_id = json_dict.get('sku_id')
        score = json_dict.get('score')
        comment = json_dict.get('comment')
        is_anonymous = json_dict.get('is_anonymous')

        # 校验参数
        if not all([order_id, sku_id, score, comment]):
            return HttpResponseForbidden("缺少必传参数")

        try:
            OrderInfo.objects.filter(order_id=order_id, user=request.user,
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden('参数order_id错误')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('参数sku_id错误')

        if is_anonymous:
            if not isinstance(is_anonymous, bool):
                return HttpResponseForbidden('参数is_anonymous错误')

        # 保存评价数据

        (OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False)
         .update(comment=comment,
                 score=score,
                 is_anonymous=is_anonymous,
                 is_commented=True))

        # 累加评论数据
        sku.comments += 1
        sku.save()

        sku.spu.comments += 1
        sku.spu.save()

        if OrderGoods.objects.filter(order_id=order_id, is_commented=False).count() == 0:
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '评价成功'})
